﻿using AntUnion.FrameWork.Model.Models;
using AntUnion.FrameWork.Util;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    [Area("Console")]
    public class CRMWalletTransactionsController : BaseController
    {
        private readonly IWebHostEnvironment _hostingEnv;
        private readonly mtContext _context;

        public CRMWalletTransactionsController(mtContext context, IWebHostEnvironment hostingEnv) : base(context, hostingEnv)
        {
            _context = context;
            _hostingEnv = hostingEnv;
        }

        public IActionResult Index(string walletId = "")
        {
            ViewBag.walletId = walletId;
            return View();
        }

        /// <summary>
        /// 获取账户列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetListJson(int page, int limit, string walletId = "", string operationType = "", string fullName = "", long? tradingAccountNo = null, string operationMode = "", string orderNumber = "", string changeTime = "")
        {
            ListResult res = new ListResult();
            try
            {
                var data = from y in _context.CrmWalletTransactions
                           join w in _context.CrmWallets on y.WalletId equals w.Id
                           join c in _context.CrmUsers on w.CrmId equals c.Id
                           join it in _context.CrmInternaltransfers on y.OrderId equals it.Id into aduit
                           from aduitData in aduit.DefaultIfEmpty()
                           join m in _context.Mt5Users on c.Id equals m.CrmId into cc
                           from ccdata in cc.DefaultIfEmpty()
                           select new
                           {
                               id = y.Id,
                               fullName = c.Name,
                               loginName = c.LoginName,
                               tradingAccount = ccdata == null ? null : (long?)ccdata.Login,
                               orderNumber = y.WalletId,
                               operationType = y.Type,
                               operationMode = y.Mode,
                               beforeAmount = y.BeforeAmount.ToString("#,##0.00") ,
                               changeAmount = y.Amount.ToString("#,##0.00") ,
                               afterAmount = y.AfterAmount.ToString("#,##0.00") ,
                               changeTime = y.CreateDate,
                               aduitRemark = _context.CrmAuditLogs.Where(k => k.OrderId == aduitData.Id && !string.IsNullOrEmpty(k.ReviewerId.ToString())).OrderByDescending(k => k.Id).Select(k => k.Remark).FirstOrDefault() == null ? y.Remark : _context.CrmAuditLogs.Where(k => k.OrderId == aduitData.Id && !string.IsNullOrEmpty(k.ReviewerId.ToString())).OrderByDescending(k => k.Id).Select(k => k.Remark).FirstOrDefault()
                               //transactionOrderNumber = y.OrderId
                           };
                if (!string.IsNullOrEmpty(walletId))
                {
                    data = data.Where(k => k.orderNumber == walletId);
                }
                if (!string.IsNullOrEmpty(operationType))
                {
                    data = data.Where(k => k.operationType == operationType);
                }
                if (!string.IsNullOrEmpty(operationMode))
                {
                    data = data.Where(k => k.operationMode == operationMode);
                }
                if (!string.IsNullOrEmpty(fullName))
                {
                    data = data.Where(k => k.fullName.Contains(fullName) || k.loginName.Contains(fullName));
                }
                if (tradingAccountNo != null)
                {
                    data = data.Where(k => k.tradingAccount == tradingAccountNo);
                }
                if (!string.IsNullOrEmpty(orderNumber))
                {
                    data = data.Where(k => k.id.Contains(orderNumber));
                }
                if (!string.IsNullOrEmpty(changeTime) && changeTime.Contains(" - "))
                {
                    string[] registrationTimes = changeTime.Split(new string[] { " - " }, StringSplitOptions.None);
                    DateTime startTime = Convert.ToDateTime(registrationTimes[0]);
                    DateTime endTime = Convert.ToDateTime(registrationTimes[1]);
                    data = data.Where(k => k.changeTime > startTime && k.changeTime < endTime);
                }
                res.Data = await data.OrderByDescending(k => k.changeTime).Skip((page - 1) * limit).Take(limit).ToArrayAsync();
                res.Code = 0;
                res.Count = data.Count();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        #region 查看详情
        public async Task<IActionResult> CrmWalletTransactionInfo(string id)
        {
            CrmWalletTransaction infoData = await _context.CrmWalletTransactions.FindAsync(id);

            if (infoData == null)
            {
                return NotFound();
            }
            CrmWallet model = await _context.CrmWallets.FindAsync(infoData.WalletId);
            if (model != null)
            {
                CrmUser crmUser = _context.CrmUsers.Where(k => k.Id == model.CrmId).FirstOrDefault();
                ViewBag.fullName = crmUser.Name;
                ViewBag.loginName = crmUser.LoginName;
                ViewBag.tradingAccount = _context.Mt5Users.Any(k => k.CrmId == model.CrmId) ? $"{_context.Mt5Users.First(k => k.CrmId == model.CrmId).Login}" : "";
                CrmInternaltransfer internaltransfer = _context.CrmInternaltransfers.FirstOrDefault(k => k.Id == infoData.OrderId);
                if (internaltransfer != null)
                {
                    CrmAuditLog auditLog = _context.CrmAuditLogs.Where(k => k.OrderId == internaltransfer.Id && !string.IsNullOrEmpty(k.ReviewerId.ToString())).FirstOrDefault();
                    if (auditLog != null)
                    {
                        ViewBag.aduitRemark = auditLog.Remark;
                        ViewBag.aduitUser = _context.TbUsers.FirstOrDefault(k => k.Id == auditLog.ReviewerId).LoginName;
                        ViewBag.aduitTime = auditLog.CreateDate;
                    }
                    else
                    {
                        ViewBag.aduitRemark = infoData.Remark;
                        ViewBag.aduitUser = infoData.Creator;
                        ViewBag.aduitTime = infoData.CreateDate;
                    }
                }
                else
                {
                    ViewBag.aduitRemark = infoData.Remark;
                    ViewBag.aduitUser = infoData.Creator;
                    ViewBag.aduitTime = infoData.CreateDate;
                }
            }
            else
            {
                ViewBag.fullName = "";
                ViewBag.loginName = "";
                ViewBag.tradingAccount = "";
                ViewBag.aduitRemark = infoData.Remark;
                ViewBag.aduitUser = infoData.Creator;
                ViewBag.aduitTime = infoData.CreateDate;
            }
            return View(infoData);
        }
        #endregion
    }
}
